# coding: utf-8
import logging
import traceback

from flask_marshmallow import base_fields

from app.extensions.api import http_exceptions
from app.modules import apis
from app.modules.api.response import default
from app.modules.common.Errors import ServiceError
from app.modules.common.utils import JsonFileUtil
from app.modules.page import service
from flask_restplus_patched import Parameters, Resource

logger = logging.getLogger(__name__)

api = apis[__name__]


class ReCreateParam(Parameters):
    menu_path = base_fields.String(
        description="菜单路径 例如:/OMS/WarehouseManage",
        missing=None,  # default value
        required=True,
    )

    file_name = base_fields.String(
        description="指定page文件, 如果文件已经存在, 会抛错",
        missing=None,  # default value
        required=True,
    )

    elements = base_fields.String(
        description="画面Content以内的所有元素内容, 以json格式定义,",
        missing=None,  # default value
        required=True,
    )

    models = base_fields.String(
        description="页面应用的model的路径, 比如models/UPS/WarehouseManage, 多个model用逗号隔开",
        missing=None,  # default value
        required=False,
    )

    workspace = base_fields.String(
        description="jsx代码的工作空间标志, 目前填default或者空都行",
        missing='default',
        required=True,
    )


class DeleteParam(Parameters):
    menuPath = base_fields.String(
        description="菜单路径 例如:OMS/WarehouseManage",
        missing=None,  # default value
        required=True,
    )

    pageName = base_fields.String(
        description="page文件的名称, 自动匹配.jsx文件",
        missing=None,  # default value
        required=True,
    )


@api.route('/recreate', methods=['GET', 'POST'])
@api.response(
    code=http_exceptions.UnprocessableEntity.code,
    description=u"重新创建页面失败",
)
class ReCreate(Resource):
    @api.parameters(ReCreateParam())
    @api.marshal_with(default(api))
    def post(self, args):

        # 2. 处理菜单文件
        try:

            menu_path = args['menu_path']
            file_name = args['file_name']
            elements = args['elements']
            models_str = args.get('models')
            models = None
            if models_str is not None:
                models = models_str.split(',')

            workspace = args['workspace']

            if JsonFileUtil.is_not_json(elements):
                raise ServiceError(
                    u"elements 必须是合法的json格式 elements:%s" % elements)

            service.recreate(path=menu_path, file_name=file_name,
                            elements=elements,models=models, workspace=workspace)

            logger.info("create page successfull!")

        except ServiceError as e:

            print e

            return {'isSuccess': False, 'msg': e.msg}
        except BaseException as e:
            print e
            return {'isSuccess': False, 'msg': traceback.format_exc()}

        return {'isSuccess': True, 'msg': 'success!'}

# @api.route('/delete')
# @api.response(
#     code=http_exceptions.UnprocessableEntity.code,
#     description="page not found.",
# )
# class Delete(Resource):
#     @api.parameters(DeleteParam())
#     @api.marshal_with(default(api))
#     def get(self, args):
#         return {'isSuccess': True, 'msg': 'success!'}
